<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="取消">

    <a-spin :spinning="confirmLoading">
      <a-form-model
        ref="form"
        :model="model"
        :rules="validatorRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol">

        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="工种名称" prop="workTypeName">
              <a-input v-model="model.workTypeName" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="产品类别" prop="productCategory">
              <a-input v-model="model.productCategory" placeholder="请输入产品类别" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="基础单价" prop="baseRate">
              <a-input-number
                v-model="model.baseRate"
                :min="0"
                :precision="2"
                placeholder="请输入基础单价"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="难度系数" prop="difficultyFactor">
              <a-input-number
                v-model="model.difficultyFactor"
                :min="0.1"
                :max="10"
                :step="0.1"
                :precision="1"
                placeholder="请输入难度系数"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="质量奖励比例" prop="qualityBonus">
              <a-input-number
                v-model="model.qualityBonus"
                :min="0"
                :max="100"
                :precision="1"
                placeholder="请输入质量奖励比例"
                style="width: 100%"
                addon-after="%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="效率奖励比例" prop="efficiencyBonus">
              <a-input-number
                v-model="model.efficiencyBonus"
                :min="0"
                :max="100"
                :precision="1"
                placeholder="请输入效率奖励比例"
                style="width: 100%"
                addon-after="%" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="生效日期" prop="effectiveDate">
              <a-date-picker
                v-model="model.effectiveDate"
                placeholder="请选择生效日期"
                style="width: 100%"
                :disabledDate="disabledStartDate" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="失效日期" prop="expiryDate">
              <a-date-picker
                v-model="model.expiryDate"
                placeholder="请选择失效日期"
                style="width: 100%"
                :disabledDate="disabledEndDate" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="状态" prop="status">
              <j-dict-select-tag
                v-model="model.status"
                dictCode="valid_status"
                placeholder="请选择状态" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="是否默认" prop="isDefault">
              <a-switch
                :checked="model.isDefault === 1"
                @change="handleIsDefaultChange"
                checked-children="是"
                un-checked-children="否" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-model-item label="备注" prop="remark">
              <a-textarea
                v-model="model.remark"
                :rows="3"
                placeholder="请输入备注信息" />
            </a-form-model-item>
          </a-col>
        </a-row>

      </a-form-model>
    </a-spin>
  </j-modal>
</template>

<script>
import { httpAction } from '@/api/manage'
import moment from 'moment'

export default {
  name: 'PieceRateStandardModal',
  data () {
    return {
      title: '操作',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
        productCategory: [
          { required: true, message: '请输入产品类别!' }
        ],
        baseRate: [
          { required: true, message: '请输入基础单价!' }
        ],
        difficultyFactor: [
          { required: true, message: '请输入难度系数!' }
        ],
        effectiveDate: [
          { required: true, message: '请选择生效日期!' }
        ],
        status: [
          { required: true, message: '请选择状态!' }
        ]
      },
      url: {
        add: '/mes/pieceRateStandard/add',
        edit: '/mes/pieceRateStandard/edit'
      }
    }
  },
  methods: {
    add (workTypeInfo) {
      this.reset()
      this.title = '新增计件标准'
      this.visible = true
      this.model.workTypeId = workTypeInfo.id
      this.model.workTypeName = workTypeInfo.workTypeName
      this.model.status = '1' // 默认有效状态
      this.model.difficultyFactor = 1.0
      this.model.qualityBonus = 0
      this.model.efficiencyBonus = 0
      this.model.effectiveDate = moment()
      this.model.isDefault = 0
    },
    edit (record) {
      this.reset()
      this.title = '编辑计件标准'
      this.visible = true
      // 深拷贝记录数据
      this.model = Object.assign({}, record)

      // 调试输出：检查原始状态值
      console.log('编辑记录 - 原始状态值:', record.status, '类型:', typeof record.status)

      // 确保状态值为字符串类型，保持与字典组件一致
      if (this.model.status !== undefined && this.model.status !== null) {
        // 处理数字类型的状态值（0->无效, 1->有效）
        if (typeof this.model.status === 'number') {
          this.model.status = this.model.status.toString()
        } else if (typeof this.model.status === 'boolean') {
          this.model.status = this.model.status ? '1' : '0'
        } else {
          this.model.status = String(this.model.status)
        }
      } else {
        // 默认设置为有效状态
        this.model.status = '1'
      }

      console.log('编辑记录 - 处理后状态值:', this.model.status)

      if (this.model.effectiveDate) {
        this.model.effectiveDate = moment(this.model.effectiveDate)
      }
      if (this.model.expiryDate) {
        this.model.expiryDate = moment(this.model.expiryDate)
      }
    },
    reset () {
      this.model = {}
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    handleOk () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl = this.url.add
            method = 'post'
          } else {
            httpurl = this.url.edit
            method = 'put'
          }

          let formData = Object.assign({}, this.model)
          if (formData.effectiveDate) {
            formData.effectiveDate = formData.effectiveDate.format('YYYY-MM-DD')
          }
          if (formData.expiryDate) {
            formData.expiryDate = formData.expiryDate.format('YYYY-MM-DD')
          }

          // 确保 isDefault 字段为整数类型
          if (formData.isDefault !== undefined && formData.isDefault !== null) {
            formData.isDefault = formData.isDefault ? 1 : 0
          }

          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              this.$message.success(res.message)
              this.$emit('ok')
              this.handleCancel()
            } else {
              this.$message.warning(res.message)
            }
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    },
    handleCancel () {
      this.reset()
      this.visible = false
    },
    disabledStartDate (startValue) {
      const endValue = this.model.expiryDate
      if (!startValue || !endValue) {
        return false
      }
      return startValue.valueOf() > endValue.valueOf()
    },
    disabledEndDate (endValue) {
      const startValue = this.model.effectiveDate
      if (!endValue || !startValue) {
        return false
      }
      return endValue.valueOf() <= startValue.valueOf()
    },
    handleIsDefaultChange(checked) {
      this.model.isDefault = checked ? 1 : 0
    }
  }
}
</script>

<style scoped>
</style>
